package com.sky.service.impl;


import com.sky.constant.MessageConstant;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.exception.InvalidFormatException;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkSpaceService workSpaceService;

    /**
     * 统计begin ~ end 区间内每天的营业额
     *
     * @param begin 起始时间
     * @param end   截至时间
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        if (begin == null || end == null || begin.isAfter(end)) {
            // 数据非法，抛出异常
            throw new InvalidFormatException(MessageConstant.NOT_ALLOW_DATA);
        }
        // 日期集合
        List<LocalDate> dateList = getLocalDateList(begin, end);

        // 每日营业额的集合
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("begin", beginTime);
            map.put("end", endTime);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 获取[begin,end]区间内的日期集合
     *
     * @param begin
     * @param end
     * @return
     */
    private static List<LocalDate> getLocalDateList(
            LocalDate begin,
            LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }


    /**
     * 用户统计接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        // 日期集合
        List<LocalDate> dateList = getLocalDateList(begin, end);
        // 每日新增用户集合
        List<Integer> newUserList = new ArrayList<>();
        // 每日全部用户集合
        List<Integer> totalUserList = new ArrayList<>();

        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap();
            map.put("end", endTime);
            Integer count = userMapper.countByMap(map);
            totalUserList.add(count);
            map.put("begin", beginTime);
            count = userMapper.countByMap(map);
            newUserList.add(count);
        }

        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    /**
     * 根据条件统计订单数量
     *
     * @param begin
     * @param end
     * @return
     */
    private Integer getOrderCountByCondition(LocalDateTime begin, LocalDateTime end, Integer status) {
        Map map = new HashMap();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", status);
        return orderMapper.countByMap(map);
    }

    /**
     * 订单统计业务
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //日期，以逗号分隔，例如：2022-10-01,2022-10-02,2022-10-03
        List<LocalDate> dateList = getLocalDateList(begin, end);
        //每日订单数，以逗号分隔，例如：260,210,215
        List<Integer> orderCountList = new ArrayList<>();
        //每日有效订单数，以逗号分隔，例如：20,21,10
        List<Integer> validOrderCountList = new ArrayList<>();
        //订单总数
        Integer totalOrderCount = 0;
        //有效订单数
        Integer validOrderCount = 0;
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            // 获取到当天的全部订单
            Integer allCount = getOrderCountByCondition(beginTime, endTime, null);
            totalOrderCount += allCount;// 总订单的数量增加
            orderCountList.add(allCount);
            // 获取当天的有效订单
            Integer validCount = getOrderCountByCondition(beginTime, endTime, Orders.COMPLETED);
            validOrderCount += validCount;// 总有效订单数增加
            validOrderCountList.add(validCount);
        }
        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(totalOrderCount != 0 ? validOrderCount * 1.0 / totalOrderCount : 0.0)
                .build();
    }


    /**
     * 获取[begin,end]时间区间内的销量top10
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> list
                = orderMapper.getSalesToop10ByCondition(beginTime, endTime);
        String nameList = StringUtils
                .join(
                        list.stream()
                                .map(GoodsSalesDTO::getName)
                                .collect(Collectors.toList()),
                        ","
                );
        String numberList = StringUtils
                .join(
                        list.stream()
                                .map(GoodsSalesDTO::getNumber)
                                .collect(Collectors.toList()),
                        ","
                );
        return SalesTop10ReportVO
                .builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 导出营业数据至Excel表格
     *
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        // 计算时间范围
        LocalDate beginTime = LocalDate.now().minusDays(30);
        LocalDate endTime = LocalDate.now().minusDays(1);

        try (
                InputStream inputStream
                        = this
                        .getClass()
                        .getClassLoader()
                        .getResourceAsStream("template/OperationDataReportTemplate.xlsx");
                XSSFWorkbook sheets = new XSSFWorkbook(inputStream)
        ) {
            XSSFSheet sheet = sheets.getSheet("Sheet1");
            // 输出时间范围
            sheet.getRow(1).getCell(1).setCellValue(beginTime.toString() + "至" + endTime.toString());
            // 获取30日的概览数据
            BusinessDataVO totalBusinessDate
                    = workSpaceService.getBusinessData(beginTime, endTime);
            // 设置概览数据
            sheet.getRow(3)
                    .getCell(2)
                    .setCellValue(totalBusinessDate.getTurnover());
            sheet.getRow(3)
                    .getCell(4)
                    .setCellValue(totalBusinessDate.getOrderCompletionRate());
            sheet.getRow(3)
                    .getCell(6)
                    .setCellValue(totalBusinessDate.getNewUsers());
            sheet.getRow(4)
                    .getCell(2)
                    .setCellValue(totalBusinessDate.getValidOrderCount());
            sheet.getRow(4)
                    .getCell(4)
                    .setCellValue(totalBusinessDate.getUnitPrice());
            for (int i = 0; i < 30; i++) {
                LocalDate begin = beginTime.plusDays(i);
                BusinessDataVO businessData = workSpaceService.getBusinessData(begin, begin);
                XSSFRow row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(begin.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            ServletOutputStream outputStream = response.getOutputStream();
            sheets.write(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
